import json

from typing import Optional, Union


def super_transfer(_type, value, default_return):
    try:
        result = _type(value)
    except (TypeError, ValueError):
        result = default_return

    return result


def safe_int(value, default=0):
    return super_transfer(int, value, default)


def safe_float(value, default=0.0):
    return super_transfer(float, value, default)


def safe_dict(value, default=None) -> dict:
    if default is None:
        default = {}
    return super_transfer(dict, value, default)


def safe_loads_json(value: Union[str, dict], default: Optional[dict] = None) -> dict:
    if default is None:
        default = {}

    if type(value) is dict:
        return value
    try:
        data: dict = json.loads(value)
        return data
    except (json.JSONDecodeError, TypeError, ValueError):
        return default
